package com.hmdp.Interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session
        HttpSession session = request.getSession();
        //2.获取session中的用户
        //Object user = session.getAttribute("user");
        //StringRedisTemplate redisTemplate =new StringRedisTemplate();

        String token = request.getHeader("Authorization");
        if(token==null){
            log.info("token不存在");
            response.setStatus(401);
            return  false;
        }
        Object user = JSON.parseObject(stringRedisTemplate.opsForValue().get(token),User.class);
        //3.判断用户是否存在
        if(user == null){
            //4.不存在，拦截，返回401状态码
            response.setStatus(401);
            return false;
        }
        User user1= (User) user;
        //5.存在，保存用户信息到Threadlocal

        UserDTO userDTO =BeanUtil.copyProperties(user1,UserDTO.class);
        UserHolder.saveUser(userDTO);
        //6.放行
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);

        //防止内存溢出
        UserHolder.removeUser();
    }
}
